package com.sri.system;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sri.business.user.UserManager;
import com.sri.cache.CacheManager;
import com.sri.formBeans.NewUserForm;

public class NewUser extends HttpServlet {
	RequestDispatcher rd;
	int stateId;

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	protected void service(HttpServletRequest req, HttpServletResponse response)
			throws ServletException, IOException {
		NewUserForm form = new NewUserForm();
		rd = req.getRequestDispatcher("/jsp/addUser.jsp");
		if (req.getParameter("stateId") != null) {
			stateId = Integer.parseInt(req.getParameter("stateId"));
			req.setAttribute("stateCities", CacheManager
					.getCitiesByStateId(stateId));
			populateForm(form, req);
		} else if (req.getParameter("dispatch") != null
				&& UserManager.addUser(populateForm(form, req))) {
			rd = req.getRequestDispatcher("/jsp/login.jsp");
		}
		req.setAttribute("registeredForm", form);
		rd.forward(req, response);
	}

	private NewUserForm populateForm(NewUserForm form, HttpServletRequest req) {
		form.setState(String.valueOf(stateId));
		form.setUserFullName(req.getParameter("userFullName"));
		form.setUserName(req.getParameter("userName"));
		form.setPassword(req.getParameter("password"));
		form.setConfPassword(req.getParameter("confPassword"));
		form.setEmail(req.getParameter("email"));
		form.setMobile(req.getParameter("mobile"));
		form.setProfession(req.getParameter("profession"));
		form.setGender(new Boolean(req.getParameter("gender")));
		form.setUserType(req.getParameter("userType"));
		form.setHouseNo(req.getParameter("houseNo"));
		form.setStreet(req.getParameter("street"));
		form.setCity(req.getParameter("city"));
		form.setZipCode(req.getParameter("zipCode"));
		return form;
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occure
	 */
	public void init() throws ServletException {
		// Put your code here
	}
}
